package link.chengguo.orangemall.service.ums.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import link.chengguo.orangemall.ApiContext;
import link.chengguo.orangemall.oms.mapper.OmsOrderMapper;
import link.chengguo.orangemall.oms.vo.OrderStstic;
import link.chengguo.orangemall.comment.SysConstant;
import link.chengguo.orangemall.ums.entity.UmsMember;
import link.chengguo.orangemall.ums.entity.UmsMemberLevel;
import link.chengguo.orangemall.ums.mapper.UmsMemberMapper;
import link.chengguo.orangemall.ums.service.IUmsMemberLevelService;
import link.chengguo.orangemall.ums.service.IUmsMemberService;
import link.chengguo.orangemall.ums.service.RedisService;
import link.chengguo.orangemall.util.JsonUtils;
import link.chengguo.orangemall.utils.StringUtils;
import link.chengguo.orangemall.vo.Rediskey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author chengguo
 * @since 2019-04-19
 */
@Service
public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember> implements IUmsMemberService {

    @Resource
    private IUmsMemberLevelService memberLevelService;
    @Resource
    private OmsOrderMapper omsOrderMapper;
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private RedisService redisService;
    @Autowired
    private ApiContext apiContext;

    @Override
    public void updataMemberOrderInfo() {
        List<OrderStstic> orders = omsOrderMapper.listOrderGroupByMemberId();
        List<UmsMemberLevel> levelList = memberLevelService.list(new QueryWrapper<UmsMemberLevel>().orderByDesc("price"));
        for (OrderStstic o : orders) {
            UmsMember member = new UmsMember();
            member.setId(o.getMemberId());
            member.setBuyMoney(o.getTotalPayAmount());
            for (UmsMemberLevel level : levelList) {
                if (member.getBuyMoney().compareTo(level.getPrice()) >= 0) {
                    member.setMemberLevelId(level.getId());
                    member.setMemberLevelName(level.getName());
                    break;
                }
            }
            member.setBuyCount(o.getTotalCount());
            memberMapper.updateById(member);
        }
    }

    @Override
    public void refreshMember(Long id) {
        UmsMember member = memberMapper.selectById(id);
        redisService.set(String.format(Rediskey.MEMBER, member.getUsername()), JsonUtils.objectToJson(member));
    }

    @Override
    public boolean saveInfo(UmsMember entity) {
        if(StringUtils.isEmpty(entity.getNickname())){
            entity.setNickname(StringUtils.ranString(SysConstant.UMS_MEMBER_NICK_SIZE));
        }
        return this.save(entity);
    }

}
